//
//  CZTabBar.swift
//  微博
//
//  Created by 范承志 on 16/6/11.
//  Copyright © 2016年 fanchengzhi. All rights reserved.
//

import UIKit

class CZTabBar: UITabBar {

    //第一步：定义闭包
    var closure:(()->())?
    
    //手写代码会掉此方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        //搭建界面
        setupUI()
    }
    
    //如果是手写代码就一定要有此方法  进行断言
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
        
//        super.init(coder: aDecoder)
//        //使用SB/XIB会调用此方法
//        setupUI()
    }
    
    //MARK 监听按钮点击
    @objc func btnClick(){
        
        //第三步：调用闭包
        closure?()
        
    }
    
    //设置button的约束
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //设置UITabBarButton宽度
        let w = CZSCREEN_W * 0.2
        
        var index: CGFloat = 0
        
        //遍历Subviews
        for value in subviews{
        
            //判断是否是系统的UITabBarButton
            if value.isKind(of: NSClassFromString("UITabBarButton")!){
                
                //设置 X 和 宽
                value.frame.size.width = w
                value.frame.origin.x = index * w
                
                index += 1
                //给撰写留个位置
                if index == 2 {
                    //在撰写位置直接进行下一个
                    index += 1
                }
            }
        }
        //设置撰写按钮的frame
        composeButton.center.x = CZSCREEN_W * 0.5
        composeButton.center.y = frame.size.height * 0.5
    }
    //MARK 搭建界面
    func setupUI(){
        
        //添加控件
        addSubview(composeButton)
    }
    
    
    
    //懒加载控件
    //撰写按钮
    lazy var composeButton: UIButton = {
        //使用分类快速创建button
        let btn = UIButton(imageName: "tabbar_compose_icon_add", backgroundImage: "tabbar_compose_button", target: self, action: #selector(btnClick))
//        //创建button
//        let btn = UIButton()
//        //设置按钮图片
//        btn.setImage(UIImage(named:"tabbar_compose_icon_add"), for: UIControlState.normal)
//        btn.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), for: UIControlState.highlighted)
//        //设置背景图片
//        btn.setBackgroundImage(UIImage(named:"tabbar_compose_button"), for: UIControlState.normal)
//        btn.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), for: UIControlState.highlighted)
//        //监听方法
//        btn.addTarget(self, action: #selector(btnClick), for: UIControlEvents.touchUpInside)
        //返回
        return btn
    }()
}
